package it.traveldream.beans;

import it.traveldream.entities.Pacchetto;
import it.traveldream.entities.Pacchetto_Personal;
import it.traveldream.entities.Richiesta;
import it.traveldream.entities.User;
import it.traveldreamClient.beans.GestoreRichiesteBeanInterface;
import it.traveldreamClient.beans.dto.PkgDTO;
import it.traveldreamClient.beans.dto.PkgPersonalDTO;
import it.traveldreamClient.beans.dto.RichiestaDTO;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


@Stateless
public class GestoreRichiesteBean implements GestoreRichiesteBeanInterface {
	@PersistenceContext EntityManager em;

	
	@Resource
	private EJBContext context;
	

	public String salvaRichiesta(RichiestaDTO RichDTO) {
		// TODO Auto-generated method stub
		Richiesta r=new Richiesta(RichDTO);
		
		r.setMittente(em.find(User.class, RichDTO.getMailMittente()));
		r.setPacchettoPersonalizzato(em.find(Pacchetto_Personal.class, RichDTO.getPkgPersonalizzato().getIdPacc()));
		
		em.persist(r);
	
		return r.getIdRichiesta();
		
	}

	public RichiestaDTO cercaRichiesta(String id) throws Exception {
		// TODO Auto-generated method stub
    	Richiesta uno = em.find(Richiesta.class, id);
    	if (uno!=null)
    		return uno.getDTO();
    	else
    		throw new Exception("Richiesta non trovata");
	}
	
	public PkgPersonalDTO getPkgPersonal(String idpkg) {
		
		Pacchetto_Personal j= new Pacchetto_Personal();
		
			j=em.find(Pacchetto_Personal.class, idpkg);
		
		return j.getDTO();
	}
	
	public int getRichiesteAccettate(PkgPersonalDTO pk){
		Richiesta rc= new Richiesta();
		
		rc= em.find(Richiesta.class, pk.getIdPacc());
		if(rc != null)
			return rc.getRichiesteAccettate();
		return 0;
	}
	
	public void incrementaRichiesteAccettate(PkgPersonalDTO pk){
		Richiesta rc= new Richiesta();
		
		
			rc= em.find(Richiesta.class, pk.getIdPacc());
		if(rc != null){
			rc.setRichiesteAccettate(rc.getRichiesteAccettate()+1);
			em.merge(rc);
		}
	}

}
